//
//  SearchViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/23.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//

#import "SearchViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "CityModel.h"
#import "ContryModel.h"
#import "PlaceModel.h"
#import "HighQualityTripModel.h"
#import "UIImageView+WebCache.h"
#import "PlaceCell.h"
#import "DestDetailViewController.h"
#import "TripViewController.h"
#import "PlaceDetailViewController.h"


@interface SearchViewController ()

@property(nonatomic, retain)NSMutableArray *dataArr;
@property(nonatomic, retain)NSMutableArray *resultArr;
// 搜索tblView
@property(nonatomic, retain)UITableView *searchTblView;

@property(nonatomic, retain)CityModel *city;
@property(nonatomic, retain)ContryModel *country;
@property(nonatomic, retain)PlaceModel *place;



@end

@implementation SearchViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArr = [NSMutableArray array];
        self.resultArr = [NSMutableArray array];
        self.country = [ContryModel contryModel];
        self.city = [CityModel cityModel];
        self.place = [[PlaceModel alloc] init];
    }
    return self;
}

-(void)data{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *strURLEncode = [self.strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager GET:strURLEncode parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"places"] count] != 0) {
            NSDictionary *tempDic = responseObject[@"places"][0];
            if ([tempDic[@"type"] integerValue]== 3 || [tempDic[@"type"] integerValue] == 2) {
                [self.city setValuesForKeysWithDictionary:responseObject[@"places"][0]];
                NSArray *arr = [NSArray arrayWithObject:self.city];
                [self.resultArr addObject:arr];
            } else if ([tempDic[@"type"] integerValue] == 1) {
                [self.country setValuesForKeysWithDictionary:responseObject[@"places"][0]];
                NSArray *arr = [NSArray arrayWithObject:self.country];
                [self.resultArr addObject:arr];
            } else {
                [self.place setValuesForKeysWithDictionary:responseObject[@"places"][0]];
                NSArray *arr = [NSArray arrayWithObject:self.place];
                [self.resultArr addObject:arr];
            }
        }
        NSArray *arr = responseObject[@"trips"];
        for (NSDictionary *dic in arr) {
            HighQualityTripModel *trip = [[HighQualityTripModel alloc] init];
            [trip setValuesForKeysWithDictionary:dic];
            [self.dataArr addObject:trip];
            [trip release];
        }
        [self.resultArr addObject:self.dataArr];
        [self.searchTblView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     
    }];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self data];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonClik:)];
    
    self.searchTblView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 70) style:UITableViewStyleGrouped];
    [self.view addSubview:self.searchTblView];
    self.searchTblView.dataSource = self;
    self.searchTblView.delegate = self;
    [_searchTblView release];
    
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.resultArr count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = [self.resultArr[section] count];
    return count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *sectionTitle = nil;
    if ([self.resultArr count] == 2) {
        if (section == 0) {
            sectionTitle = @"搜索结果";
        } else {
            sectionTitle = @"途行日记";
        }
    } else if ([self.resultArr[0] count] == 0){
        sectionTitle = @"亲,什么都没有了";
    } else {
        sectionTitle = @"途行日记";
    }
    return sectionTitle;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"searchTblViewCell";
    PlaceCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[PlaceCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    if (indexPath.section == 0 && self.resultArr.count == 2) {
        if ([self.country name]) {
            cell.nameLbl.text = self.country.name;
            [cell.destImgView sd_setImageWithURL:[NSURL URLWithString:[self.country icon]] placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
        } else if ([self.city name]) {
            cell.nameLbl.text = self.city.name;
            [cell.destImgView sd_setImageWithURL:[NSURL URLWithString:[self.city icon]] placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
        } else {
            cell.nameLbl.text = self.place.name;
            [cell.destImgView sd_setImageWithURL:[NSURL URLWithString:[self.place icon]] placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
        }
    } else {
        HighQualityTripModel *trip = self.resultArr[indexPath.section][indexPath.row];
        cell.nameLbl.text = [trip name];
        [cell.destImgView sd_setImageWithURL:[NSURL URLWithString:[trip cover_image_w640]] placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        if ([self.resultArr count] == 2) {
            if (indexPath.section == 0) {
                if ([self.resultArr[indexPath.row][0] isKindOfClass:[ContryModel class]]) {
                    DestDetailViewController *destDetail = [[DestDetailViewController alloc] init];
                    ContryModel *country = self.resultArr[indexPath.row][0];
                    // 地点id
                    destDetail.destId = [country countryId];
                    // 地点类型
                    destDetail.type = [NSString stringWithFormat:@"%ld", [country type]];
                    [self.navigationController pushViewController:destDetail animated:YES];
                    [destDetail release];
                    // 如果是城市
                } else if ([self.resultArr[indexPath.row][0] isKindOfClass:[CityModel class]]){
                    DestDetailViewController *destDetail = [[DestDetailViewController alloc] init];
                    CityModel *city = self.resultArr[indexPath.row][0];
                    // 地点id
                    destDetail.destId = [NSString stringWithFormat:@"%@", [city cityId]];
                    // 地点类型
                    destDetail.type = [NSString stringWithFormat:@"%ld", [city type]];
                    [self.navigationController pushViewController:destDetail animated:YES];
                    [destDetail release];
                } else {
                    PlaceDetailViewController *placeDetailVC = [[PlaceDetailViewController alloc] init];
                    PlaceModel *place = self.resultArr[indexPath.row][0];
                    // 类型
                    placeDetailVC.type = [NSString stringWithFormat:@"%ld", place.type];
                    // 地点id
                    placeDetailVC.placeId = [NSString stringWithFormat:@"%@", place.placeId];
                    [self.navigationController pushViewController:placeDetailVC animated:YES];
                    [placeDetailVC release];
                }
                
            } else {
                TripViewController *tripVC = [[TripViewController alloc] init];
                HighQualityTripModel *trip = self.dataArr[indexPath.row];
                tripVC.highQualityTripModelId = [NSString stringWithFormat:@"%@", [trip highQualityTripModelId]];
                tripVC.htmlLatsStr = @"trackpoints";
                [self.navigationController pushViewController:tripVC animated:YES];
                [tripVC release];
            }
        } else {
            TripViewController *tripVC = [[TripViewController alloc] init];
            HighQualityTripModel *trip = self.dataArr[indexPath.row];
            tripVC.highQualityTripModelId = [NSString stringWithFormat:@"%@", [trip highQualityTripModelId]];
            tripVC.htmlLatsStr = @"trackpoints";
            [self.navigationController pushViewController:tripVC animated:YES];
            [tripVC release];
        }
}

// rightButton 的方法
-(void)rightButtonClik:(UIButton *)button{
    self.field.backgroundColor = [UIColor cyanColor];
    self.field.layer.borderWidth = 1;
    self.field.enabled = YES;
    
    [self.navigationController popViewControllerAnimated:YES];
       
}

// 设置白天模式
- (void)setLightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
    
}

// 设置夜间模式
- (void)setNightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
}

-(void)dealloc{

    [_dataArr release];
    [_resultArr release];
    [_searchTblView release];
    [_city release];
    [_country release];
    [_place release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
